package com.define.ssh.action.upgrade;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.StringUtils;

import com.define.ssh.action.admin.BaseAdminAction;
import com.define.ssh.model.ClientUpdateInfo;
import com.define.ssh.model.ClientVersionInfo;
import com.define.ssh.model.Compdept;
import com.define.ssh.model.DeptAccount;
import com.define.ssh.model.MWarnTarget;
import com.define.ssh.model.Terminalparam;
import com.define.ssh.model.UserInfo;
import com.define.ssh.service.ClientUpdateInfoService;
import com.define.ssh.service.ClientVersionInfoService;
import com.define.ssh.service.CompdeptService;
import com.define.ssh.util.SystemUtil;


/**
 *  
 * 
 */
@ParentPackage("admin")
public class ClientVersionAction extends BaseAdminAction {
	
	private static final long serialVersionUID = 4L;
	/** 页面传递参数过来*/
	protected int pageSize;
	protected int pageNum;
	
	private String deptIds;
	
	private String clientType="3";
	
	@Resource(name = "compdeptServiceImpl")
	private CompdeptService compdeptService;
	
	@Resource(name = "clientUpdateInfoServiceImpl")
	private ClientUpdateInfoService clientUpdateInfoService;
	
	@Resource(name = "clientVersionInfoServiceImpl")
	private ClientVersionInfoService clientVersionInfoService;
	
	private List  deptList=new ArrayList();
	private ClientVersionInfo clientVersionInfo=new ClientVersionInfo(); 
	private String ver_num="";
	private String utype;
	

	/**
	 * 列表页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() {
		
		if(clientType==null){
			clientType="3";
		}
	
		UserInfo	 userinfo=(UserInfo)super.getRequest().getSession().getAttribute(SystemUtil.USERINFO);
		if(userinfo!=null){
	
			
			 DetachedCriteria dt = DetachedCriteria.forClass(ClientVersionInfo.class);	
			 dt.add(Restrictions.eq("userId",  Integer.valueOf(userinfo.getId().toString())));
			 dt.add(Restrictions.eq("clientType",  clientType));
			 dt.addOrder(Order.desc("updateTime")); 
			List  cvList=compdeptService.findByCriteria(dt);
		if(cvList.size()>0){
		for (int i = 0; i < cvList.size(); i++) {
			 clientVersionInfo=(ClientVersionInfo)  cvList.get(0);
			 System.out.println("clientVersionInfo===="+clientVersionInfo.getFullVerNum());
			ver_num=clientVersionInfo.getFullVerNum();
		}
	   }
		}
		if(clientType.equals("3")){
			return "winClientVersion";
		}
		return "clientVersion";
	}
	
	
	/**
	 * 取部门树数据
	 * @return
	 */
	public String getDeptTree(){
		
		String type="";
		
		UserInfo	 userinfo=(UserInfo)super.getRequest().getSession().getAttribute(SystemUtil.USERINFO);
		if(userinfo!=null){
			System.out.println("======="+userinfo.getRole().getName());
				/*	"1""超级管理员"	
				"2" "系统管理员"
				"3""部门管理员"
				"4""操作员"*/
				if(userinfo.getRole()!=null&&(userinfo.getRole().getId()==1||userinfo.getRole().getId()==2)){
					//deptList.add("所有部门");
					deptList=this.compdeptService.getAllList();
					type="1";
			}else{
				
				
				
				 DetachedCriteria dt = DetachedCriteria.forClass(DeptAccount.class);	
				 dt.add(Restrictions.eq("userid",  Integer.valueOf(userinfo.getId().toString())));
				 deptList=compdeptService.findByCriteria(dt);
				 type="2";
			}
			
		}
		
		
		//List<Compdept> list=this.compdeptService.getAllList();
		StringBuffer sb=new StringBuffer();
		sb.append("[");
		for(int i=0;i<deptList.size();i++){
			if(type.equals("2")){
			DeptAccount depa=(DeptAccount)deptList.get(i);
			Compdept dept=depa.getCompdept();
			
			sb.append("{");
			sb.append("id:"+dept.getId());
			sb.append(",pId:"+dept.getPid());
			sb.append(",name:\""+dept.getDeptname()+"\"");
			if(dept.getPid().equals("0")){
				sb.append(",open:true");
			}
			sb.append("}");
			if(i!=deptList.size()-1){
				sb.append(",");
			}
			}else{
				
				Compdept dept=(Compdept)deptList.get(i);
				
				sb.append("{");
				sb.append("id:"+dept.getId());
				sb.append(",pId:"+dept.getPid());
				sb.append(",name:\""+dept.getDeptname()+"\"");
				if(dept.getPid().equals("0")){
					sb.append(",open:true");
				}
				sb.append("}");
				if(i!=deptList.size()-1){
					sb.append(",");
				}	
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	
	
	/**
	 * 取关联的部门数据
	 * @return
	 */
	public String getDeptTreeIds(){
		StringBuffer sb=new StringBuffer();
		UserInfo	 userinfo=(UserInfo)super.getRequest().getSession().getAttribute(SystemUtil.USERINFO);
		if(userinfo!=null){
	
			
		if(ver_num!=null&&!ver_num.equals("")){
		
			
		HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("userId", Integer.valueOf(userinfo.getId().toString()));
		searchMap.put("verNum", ver_num);
		searchMap.put("clientType", clientType);
		List<ClientUpdateInfo> list=this.clientUpdateInfoService.getAllListByParameter(searchMap);
		
		sb.append("[");
		for(int i=0;i<list.size();i++){
			ClientUpdateInfo du=list.get(i);
			sb.append("{");
			sb.append("id:"+du.getDeptUserId());
			sb.append("}");
			if(i!=list.size()-1){
				sb.append(",");
			}
		}
		sb.append("]");
		
		}
		}
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	
	
	//保存
	public String save() {
		
		try {
			
		
		
		UserInfo	 userinfo=(UserInfo)super.getRequest().getSession().getAttribute(SystemUtil.USERINFO);
		
		
		 String[] qlUrl = super.getRequest().getParameterValues("qlUrl");
		 String[] zlUrl = super.getRequest().getParameterValues("zlUrl");
		String verNum = super.getRequest().getParameter("verNum");
		String fullUrl = super.getRequest().getParameter("fullUrl");//
		String updateFlag = super.getRequest().getParameter("updateFlag");//
		String remindTime = super.getRequest().getParameter("remindTime");
		
	
		if(clientType==null){
			clientType="3";
		}
		
		String radio = super.getRequest().getParameter("radio");//升级范围  0全部升级  1 部分升级
		
		if(verNum!=null){
			
			 DetachedCriteria dt = DetachedCriteria.forClass(ClientVersionInfo.class);	
			 dt.add(Restrictions.eq("userId",  Integer.valueOf(userinfo.getId().toString())));
			 dt.add(Restrictions.eq("clientType", clientType));
			 dt.add(Restrictions.eq("fullVerNum", verNum));
			 List  cvList=compdeptService.findByCriteria(dt);
			if(cvList.size()>0){
				return ajax("版本号已存在请重新输入！");
			}
		}
		
		Long time=System.currentTimeMillis()/1000;
		
		ClientVersionInfo cversion=new ClientVersionInfo();
		if(StringUtils.hasText(updateFlag)&&updateFlag.equals("2")){
			cversion.setRemindTime(remindTime);
		}
		
		if(qlUrl!=null&&qlUrl.length>0){
			if(qlUrl.length==1){
				
			cversion.setQlUrl1(qlUrl[0]);
			
			}else if(qlUrl.length==2){
				
			cversion.setQlUrl1(qlUrl[0]);
			cversion.setQlUrl2(qlUrl[1]);
				
			}else if(qlUrl.length==3){
			cversion.setQlUrl1(qlUrl[0]);
			cversion.setQlUrl2(qlUrl[1]);
			cversion.setQlUrl3(qlUrl[2]);
				
			}else if(qlUrl.length==4){
			cversion.setQlUrl1(qlUrl[0]);
			cversion.setQlUrl2(qlUrl[1]);
			cversion.setQlUrl3(qlUrl[2]);
			cversion.setQlUrl4(qlUrl[3]);
				
			}else if(qlUrl.length==5){
			cversion.setQlUrl1(qlUrl[0]);
			cversion.setQlUrl2(qlUrl[1]);
			cversion.setQlUrl3(qlUrl[2]);
			cversion.setQlUrl4(qlUrl[3]);
			cversion.setQlUrl5(qlUrl[4]);
			}
			
		}
		
		
		if(zlUrl!=null&&zlUrl.length>0){
			if(zlUrl.length==1){
				
			cversion.setZlUrl1(zlUrl[0]);
			
			}else if(zlUrl.length==2){
				
			cversion.setZlUrl1(zlUrl[0]);
			cversion.setZlUrl2(zlUrl[1]);
				
			}else if(zlUrl.length==3){
			cversion.setZlUrl1(zlUrl[0]);
			cversion.setZlUrl2(zlUrl[1]);
			cversion.setZlUrl3(zlUrl[2]);
				
			}else if(zlUrl.length==4){
			cversion.setZlUrl1(zlUrl[0]);
			cversion.setZlUrl2(zlUrl[1]);
			cversion.setZlUrl3(zlUrl[2]);
			cversion.setZlUrl4(zlUrl[3]);
				
			}else if(zlUrl.length==5){
			cversion.setZlUrl1(zlUrl[0]);
			cversion.setZlUrl2(zlUrl[1]);
			cversion.setZlUrl3(zlUrl[2]);
			cversion.setZlUrl4(zlUrl[3]);
			cversion.setZlUrl5(zlUrl[4]);
			}
			
		}
		if(fullUrl!=null){
			cversion.setFullUrl(fullUrl);
		}else{
			cversion.setFullUrl("");
		}
		
		cversion.setFullVerNum(verNum);
		cversion.setClientType(clientType);//'客户端类型：1:Android,2:IOS,3 PC 4.mac 5.windowsphone',
	    cversion.setEnableFlag("1");// '版本启用标识：0停用 1 启用',
	    cversion.setEnableTime(Integer.valueOf(time.toString()));//'版本生效时间',
	    cversion.setUpdateType("1");// '1 新增 2 修改 3 删除',
	    cversion.setUpdateTime(new Date());
	    cversion.setDescription("");
	    cversion.setUserId(Integer.parseInt(userinfo.getId().toString()));
	    Date updatetime = clientUpdateInfoService.getUpdateTime("client_version_info");
	    clientVersionInfoService.save(cversion);
	 
	    if(radio.equals("1")){
		for(String deptid:deptIds.split(",")){
			if(!deptid.equals("")){
				ClientUpdateInfo du=new ClientUpdateInfo();
				du.setDeptUserId(Integer.parseInt(deptid));
				Integer userid=Integer.parseInt(userinfo.getId()+"");
				du.setUserId(userid);
				du.setUpdateTime(new Date());
				du.setIdType("1");//类型 0全部 1部门 2用户 3固定组',
				du.setUpdateFlag(updateFlag);//'升级类型 0:非强制升级,1:强制升级,2静默升级',
				du.setClientType(clientType);
				du.setVerNum(verNum);
				du.setUpdateType("1");// '1 新增 2 修改 3 删除',
				du.setUpdateTime(new Date());
				du.setGroupId("");
				du.setSilenceTime(0);
				this.clientUpdateInfoService.save(du);
			}
		}
	    }else if(radio.equals("0")){
	    	
	    	
			ClientUpdateInfo du=new ClientUpdateInfo();
			du.setDeptUserId(0);
			Integer userid=Integer.parseInt(userinfo.getId()+"");
			du.setUserId(userid);
			du.setUpdateTime(new Date());
			du.setIdType("0");//类型 0全部 1部门 2用户 3固定组',
			du.setUpdateFlag(updateFlag);//'升级类型 0:非强制升级,1:强制升级,2静默升级',
			du.setClientType(clientType);
			du.setVerNum(verNum);
			du.setUpdateType("1");// '1 新增 2 修改 3 删除',
			du.setGroupId("");
			du.setSilenceTime(0);
			
			this.clientUpdateInfoService.save(du);
	    }
	    Long modfiytime = updatetime.getTime() / 1000;
	    clientUpdateInfoService.connectInterfce("client_version_info", 1017,modfiytime.intValue());
	   
	   
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return ajax("恭喜您，发布版本成功！");
	}

	
	
	public String versionList(){
		
		
		try {
			
			HashMap<String, Object> searchMap = new HashMap<String, Object>();
			if(StringUtils.hasText(utype)){
				 searchMap.put("clientType",utype);
				}
			 searchMap.put("updateType","1");
			pager.setOrder(com.define.ssh.util.Pager.Order.desc);
			pager.setOrderBy("updateTime");
			pager.setSearchMap(searchMap);
			pager =clientVersionInfoService.findPager(pager);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "clientVersionList";
	}
	
	
	/****
	 * 删除
	 */
	public String delete() {
		
		try {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");  
		response.setCharacterEncoding("UTF-8");
		
		String id = super.getRequest().getParameter("id");
		 DetachedCriteria dt = DetachedCriteria.forClass(ClientVersionInfo.class);	
		 dt.add(Restrictions.eq("id",Integer.valueOf(id)));
		 List<ClientVersionInfo> userlist=clientVersionInfoService.findByCriteria(dt);
		 if(userlist!=null&&userlist.size()>0){
			 Date updatetime = clientUpdateInfoService.getUpdateTime("client_version_info");
			 ClientVersionInfo mwl= userlist.get(0);
			// clientVersionInfoService.delete(mwl);
			 mwl.setUpdateType("3");////更新标示 1新增  2修改  3删除
			 mwl.setUpdateTime(new Date());
			 clientVersionInfoService.update(mwl);
			 Long modfiytime = updatetime.getTime() / 1000;
			 clientUpdateInfoService.connectInterfce("client_version_info", 1017,modfiytime.intValue());
			 response.getWriter().write("true");
		 }
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/****
	 * 修改状态
	 */
	public String updateState() {

		try {

			String id = super.getRequest().getParameter("id");
			
			String enableFlag = super.getRequest().getParameter("enableFlag");//enableFlag 1启用，0停用
			 DetachedCriteria dt = DetachedCriteria.forClass(ClientVersionInfo.class);	
			 dt.add(Restrictions.eq("id",Integer.valueOf(id)));
			 List<ClientVersionInfo> userlist=clientVersionInfoService.findByCriteria(dt);
			 if(userlist!=null&&userlist.size()>0){
				 ClientVersionInfo mwarntarget= userlist.get(0);
				 
			
			if (mwarntarget != null && StringUtils.hasText(enableFlag)) {
				Date updatetime = clientUpdateInfoService.getUpdateTime("client_version_info");
				if (enableFlag.equals("0")) {
					mwarntarget.setEnableFlag("1");
					mwarntarget.setUpdateType("2");////更新标示 1新增  2修改  3删除
					mwarntarget.setUpdateTime(new Date());
					clientVersionInfoService.update(mwarntarget);
					return ajax("启用成功!");
				} else if (enableFlag.equals("1")) {
					mwarntarget.setEnableFlag("0");
					mwarntarget.setUpdateType("2");////更新标示 1新增  2修改  3删除
					mwarntarget.setUpdateTime(new Date());
					clientVersionInfoService.update(mwarntarget);
					return ajax("禁用成功!");
				}
				 Long modfiytime = updatetime.getTime() / 1000;
				 clientUpdateInfoService.connectInterfce("client_version_info", 1017,modfiytime.intValue());
				
			}
			 }

		} catch (final Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	public List getDeptList() {
		return deptList;
	}


	public void setDeptList(List deptList) {
		this.deptList = deptList;
	}


	public String getDeptIds() {
		return deptIds;
	}


	public void setDeptIds(String deptIds) {
		this.deptIds = deptIds;
	}


	public String getClientType() {
		return clientType;
	}


	public void setClientType(String clientType) {
		this.clientType = clientType;
	}


	public ClientVersionInfo getClientVersionInfo() {
		return clientVersionInfo;
	}


	public void setClientVersionInfo(ClientVersionInfo clientVersionInfo) {
		this.clientVersionInfo = clientVersionInfo;
	}


	public String getVer_num() {
		return ver_num;
	}


	public void setVer_num(String ver_num) {
		this.ver_num = ver_num;
	}


	public String getUtype() {
		return utype;
	}


	public void setUtype(String utype) {
		this.utype = utype;
	}



	
	
	
}